from pymysql import *
from settings import *


class MysqlHelper(object):
    def __init__(self):
        self.conn = connect(
            host=MYSQL_HOST,
            port=MYSQL_PORT,
            user=MYSQL_USER,
            password=MYSQL_PASSWORD,
            database=MYSQL_DATABASE,
            charset='utf8',
            cursorclass=cursors.DictCursor
        )
        self.cursor = self.conn.cursor()

    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def get_one(self, sql, params=()):
        try:
            self.cursor.execute(sql, params)
            result = self.cursor.fetchone()
        except Exception as e:
            return e
        return result

    def get_all(self, sql, params=()):
        try:
            self.cursor.execute(sql, params)
            list_data = self.cursor.fetchall()
        except Exception as e:
            return e
        return list_data

    def insert(self, sql, params=()):
        return self.__edit(sql, params)

    def delete(self, sql, params=()):
        return self.__edit(sql, params)

    def update(self, sql, params=()):
        return self.__edit(sql, params)

    def __edit(self, sql, params):
        try:
            count = self.cursor.execute(sql, params)
            self.conn.commit()
            return count
        except Exception as e:
            return e
